package com.cn.springcloudshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.cn.springcloudshop.common.*;
import com.cn.springcloudshop.model.*;
import com.cn.springcloudshop.service.inter.*;
import jdk.nashorn.internal.objects.annotations.Where;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.bridge.MessageWriter;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.HEAD;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.util.*;

/**
 * @Author: wuyanzu
 * @Date: 2018/8/1
 */
@RequestMapping("/order/")
@RestController
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    ProductService productService;

    @Autowired
    ReceivingAddressService receivingAddressService;

    @Autowired
    OrderProductService orderProductService;

    @Autowired
    ShopCarService shopCarService;

    @Autowired
    WeChatFeignClient weChatFeignClient;

  /*  @RequestMapping("getUser")
    public AjaxRes getYmUser(AjaxRes ajaxRes,HttpServletRequest request){
        System.out.println(request.getSession().getId());
        YmUser ymUser = getYmUser(request);
        ajaxRes.setSucceed(ymUser,Const.DATA_SUCCEED);
        return ajaxRes;
    }
    @RequestMapping("setUser")
    public AjaxRes setUser(String user,AjaxRes ajaxRes,HttpServletRequest request){
        System.out.println(request.getSession().getId());
        YmUser ymUser = JSONObject.parseObject(user,YmUser.class);
      //  System.err.println(ymUser.getUserId());
        request.getSession().setAttribute("user",ymUser);
        ajaxRes.setSucceed(user,Const.SAVE_SUCCEED);
        return ajaxRes;
    }*/


    @RequestMapping("exeit")
    public boolean isExeit(Long orderId) {
        YmShopOrder order = orderService.selectByPrimaryKey(orderId);
        if (order.getShopOrderWaterid() != null) {
            System.err.println(order.getShopOrderWaterid());
            return true;
        } else {
            return false;
        }
    }

  /**
  *
  * 支付成功回调
  * @author wuyanzu
  * @date 2018/9/3 10:54
  * @param [request, response]
  * @return java.lang.String
  */
    @RequestMapping("payCallback")
    synchronized public void payCallback(@RequestBody Map<String, Object> map) throws IOException, SAXException, ParserConfigurationException {
        try {
            for (String key : map.keySet()) {
                System.out.println(key + "->====================" + map.get(key));
            }
            if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
                //订单id
                Long orderId = Long.valueOf(map.get("attach").toString().split(",")[0].toString());
                if (orderId != null) {
                    YmShopOrder order = orderService.selectByPrimaryKey(orderId);
                    System.err.println(order);
                    System.err.println(order.getShopOrderWaterid());
                    if (order.getShopOrderWaterid() != null) {
                        System.err.println("==========asdfgbhjksdfbgsdyu");
                        return ;
                    }else {
                        if (order != null) {
                            System.err.println("订单号======"+orderId);
                            YmShopOrderProductExample ymShopOrderProductExample = new YmShopOrderProductExample();
                            ymShopOrderProductExample.createCriteria().andShopOrderIdEqualTo(orderId);
                            List<YmShopOrderProduct> orderProducts = orderProductService.selectByExample(ymShopOrderProductExample);
                            if (orderProducts != null && orderProducts.size() > 0) {
                                List<YmShopProduct> products = new ArrayList<>();
                                for (YmShopOrderProduct orderProduct : orderProducts) {
                                    YmShopProduct product = productService.selectByPrimaryKey(orderProduct.getShopProductId());
                                    product.setSalesVolume(orderProduct.getShopProductNumber() + product.getSalesVolume());
                                    product.setProductNumber(product.getProductNumber() - orderProduct.getShopProductNumber());
                                    products.add(product);
                                }
                                if (productService.updateBatchByPK(products) == products.size()) {
                                    System.err.println("修改订单信息===");
                                    //订单金额
                                    Integer totalFee = Integer.valueOf(map.get("total_fee").toString());
                                    //现金支付金额
                                    Integer cashFee = Integer.valueOf(map.get("cash_fee").toString());
                                    //微信订单号
                                    String transactionId = map.get("transaction_id").toString();
                                    //商户订单号
                                    String outTrade_No = map.get("out_trade_no").toString();
                                    //支付完成时间
                                    String timeEnd = map.get("time_end").toString();
                                    //预支付id
                                    // String prepayId = map.get("prepay_id").toString();
                                    DateFormat format= new SimpleDateFormat("yyyyMMddHHmmss");
                                    order.setShopOrderStatus("pendingDelivery");
                                    order.setShopOrderPayMethod("weixin");
                                    order.setShopOrderTotalcost((long) (totalFee));
                                    order.setShopOrderProductcost((long) (totalFee));
                                    order.setShopOrderPayTime(format.parse(timeEnd));
                                    // order.setShopOrderPrepayid(prepayId);
                                    order.setShopOrderWaterid(transactionId);
                                    weChatFeignClient.insertUserPoint(order.getUserId(), "积分兑换商品", null, "-" + order.getShopOrderPoint());
                                    System.err.println("添加对应积分记录==================================");
                                    orderService.updateByPrimaryKey(order);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("wechatPay")
    public AjaxRes pay(AjaxRes ajaxRes,HttpServletRequest request,Long orderId,String ymUser) {
        if (orderId != null) {
            YmShopOrder order = orderService.selectByPrimaryKey(orderId);
            YmUser user = ShopCarController.getYmUser(ymUser);
            System.err.println(user.getUserId()+"==============");
            if (order != null && user != null) {
                String body = "购买商品";
                Map<Object, Object> map = weChatFeignClient.pay(request, order.getShopOrderTotalcost().intValue(), body, orderId, user.getRegisterChannelId());
                for (Map.Entry<Object, Object> m : map.entrySet()) {
                    System.err.println(m.getValue());
                }
                if (map != null) {
                    ajaxRes.setSucceed(map);
                } else {
                    ajaxRes.setFailMsg("支付失败");
                }
            } else {
                ajaxRes.setFailMsg("用户或订单信息有误");
            }
        }
        return ajaxRes;
    }
    /**
    *
    * 修改订单信息
    * @author wuyanzu
    * @date 2018/8/23 15:03
    * @param [ajaxRes, orderId, update]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("del")
    public AjaxRes delOrder(AjaxRes ajaxRes, Long orderId,@RequestParam(required = false) Long update,@RequestParam(required = false)String pay) {
        if (orderId != null) {
            YmShopOrder order = orderService.selectByPrimaryKey(orderId);
            if (update != null) {
                order.setShopOrderStatus("theEnd");
            } else {
                order.setShopOrderState("N");
                order.setShopOrderStatus("fail");
                order.setShopOrderRemarks("用户取消或删除订单");
            }
            if (orderService.updateByPrimaryKey(order) == 1) {
                ajaxRes.setSucceedMsg(Const.UPDATE_SUCCEED);
            } else {
                ajaxRes.setFailMsg(Const.UPDATE_FAIL);
            }
        } else {
            ajaxRes.setFailMsg(Const.PARAMETER_NULL);
        }
        return ajaxRes;
    }
    /**
    *
    * 获取用户基本信息和积分
    * @author wuyanzu
    * @date 2018/8/23 11:38
    * @param [ajaxRes]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("user")
    public AjaxRes getUser(AjaxRes ajaxRes,String ymUser) {
        YmUser user = ShopCarController.getYmUser(ymUser);
        if (user != null) {
            System.err.println(user.getUserId()+"==============");
            HashMap<String, Object> map = new HashMap<>();
            map.put("pic", user.getHeadimgurl());
            map.put("point", weChatFeignClient.getPoint(user.getUserId()));
            map.put("name", user.getNickname());
            ajaxRes.setSucceed(map);
        } else {
            ajaxRes.setFailMsg("用户信息有误");
        }
        return ajaxRes;
    }

    /**
    *
    * 根据订单id获取订单详情
    * @author wuyanzu
    * @date 2018/8/23 14:41
    * @param [ajaxRes, orderid]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("orderDetails")
    public AjaxRes getDetails(AjaxRes ajaxRes, Long orderid) {
        if (orderid == null) {
            ajaxRes.setFailMsg(Const.PARAMETER_NULL);
            return ajaxRes;
        }
        YmShopOrder order = orderService.selectByPrimaryKey(orderid);
        if (order == null) {
            ajaxRes.setFailMsg(Const.DATA_FAIL);
            return ajaxRes;
        }
        order = GetOrderDetails(order);
        ajaxRes.setSucceed(order, Const.DATA_SUCCEED);
        return ajaxRes;
    }

    /**
    *
    * 获取订单详情
    * @author wuyanzu
    * @date 2018/8/23 15:03
    * @param [order]
    * @return com.cn.springcloudshop.model.YmShopOrder
    */
    private YmShopOrder GetOrderDetails(YmShopOrder order) {
        if (order.getShopOrderTime() != null) {
            order.setShowOrderTime(DateUtils.formatDate(order.getShopOrderTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if ("point".equals(order.getShopOrderPayMethod())) {
            order.setPayType(0L);
        } else {
            order.setPayType(1L);
        }
        List<OrderProductVo> vos = new ArrayList<>();
        YmShopOrderProductExample example = new YmShopOrderProductExample();
        example.createCriteria().andShopOrderIdEqualTo(order.getShopOrderId());
        List<YmShopOrderProduct> orderProducts = orderProductService.selectByExample(example);
        for (YmShopOrderProduct orderProduct : orderProducts) {
            YmShopProduct product = productService.selectByPrimaryKey(orderProduct.getShopProductId());
            OrderProductVo vo = new OrderProductVo();
            if ("point".equals(order.getShopOrderPayMethod())) {
                vo.setPoint(product.getProductPoint());
                vo.setPrice(0L);
                vo.setPayMethod(0);
            } else {
                vo.setPoint(product.getProductPoint());
                vo.setPrice(product.getProductPrice());
                vo.setPayMethod(1);
            }
            vo.setName(product.getProductName());
            vo.setNumber(orderProduct.getShopProductNumber());
            vo.setProPic(product.getProductPic());
            vos.add(vo);
        }
        order.setOrderProductVos(vos);
        return order;
    }

    /**
    *
    * 根据用户id查询订单信息
    * @author wuyanzu
    * @date 2018/8/23 10:11
    * @param [ajaxRes, shopOrderStatus]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("getAll")
    public AjaxRes getAllOrders(AjaxRes ajaxRes,String ymUser,@RequestParam(required = false)String shopOrderStatus,int pageNumber) {
        int pageSize = 5;
        YmUser user = ShopCarController.getYmUser(ymUser);
        System.err.println(user.getUserId()+"==============");
        if (user != null) {
            YmShopOrderExample ymShopOrderExample = new YmShopOrderExample();
            ymShopOrderExample.setDistinct(true);
            ymShopOrderExample.setOrderByClause("shop_order_time desc");
            if (StringUtils.isNotEmpty(shopOrderStatus)) {
                ymShopOrderExample.createCriteria().andShopOrderStateEqualTo("Y").andUserIdEqualTo(user.getUserId()).andShopOrderStatusEqualTo(shopOrderStatus);
            } else {
                ymShopOrderExample.createCriteria().andShopOrderStateEqualTo("Y").andUserIdEqualTo(user.getUserId());
            }
            if (pageNumber == 1) {
                ymShopOrderExample.setLimit(0);
                ymShopOrderExample.setOffset(pageSize);
            } else {
                ymShopOrderExample.setLimit(pageNumber * pageSize - 1);
                ymShopOrderExample.setOffset(pageSize);
            }
            List<YmShopOrder> list = orderService.selectByExample(ymShopOrderExample);
            if (list != null && list.size() > 0) {
                for (YmShopOrder order : list) {
                    order = GetOrderDetails(order);
                }
                ajaxRes.setSucceed(list, Const.DATA_SUCCEED);
            } else {
                ajaxRes.setSucceedMsg("暂无订单信息");
            }
        } else {
            ajaxRes.setFailMsg("用户信息有误");
        }

        return ajaxRes;
    }

    /**
     * 根据订单状态查询对应订单数量
     *
     * @param [ajaxRes]
     * @return com.cn.springcloudshop.common.AjaxRes
     * @author wuyanzu
     * @date 2018/8/15 15:43
     */
    @RequestMapping("getCont")
    public AjaxRes getContByStatus(AjaxRes ajaxRes, String ymUser) {
        YmUser user = ShopCarController.getYmUser(ymUser);
        System.err.println(user.getUserId()+"==============");
        if (user != null) {
            List<CountOrderStatusPOJO> list = orderService.countByStatus(user.getUserId());
            if (list != null && list.size() > 0) {
                Map<String, Integer> map = new HashMap<>();
                for (CountOrderStatusPOJO countOrderStatusPOJO : list) {
                    map.put(countOrderStatusPOJO.getShopOrderStatus(), countOrderStatusPOJO.getNumber());
                }
                ajaxRes.setSucceed(map);
            } else {
                ajaxRes.setSucceedMsg("暂无订单信息");
            }
        } else {
            ajaxRes.setFailMsg("用户信息有误");
        }
        return ajaxRes;
    }


    /**
    *
    * 根据订单状态查询对应订单信息
    * @author wuyanzu
    * @date 2018/8/15 14:41
    * @param [ajaxRes, status]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("getByStatus")
    public AjaxRes getOrderByType(AjaxRes ajaxRes, String status) {
        YmShopOrderExample ymShopOrderExample = new YmShopOrderExample();
        ymShopOrderExample.createCriteria().andShopOrderStatusEqualTo(status);
        List<YmShopOrder> list = orderService.selectByExample(ymShopOrderExample);
        if (list != null && list.size() > 0) {
            ajaxRes.setSucceed(list, Const.DATA_SUCCEED);
        } else {
            ajaxRes.setSucceedMsg("暂无" + getFileName(status));
        }
        return ajaxRes;
    }
    /**
    *
    * 订单信息查询
    * @author wuyanzu
    * @date 2018/8/9 11:51
    * @param [ajaxRes, shopOrderStatus, shopOrderFlowno, pageNum, pageSize]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("conditionalQuery")
    public AjaxRes conditionalQuery(AjaxRes ajaxRes,@RequestParam(required = false)String shopOrderStatus,@RequestParam(required = false)String shopOrderFlowno,
                                    @RequestParam(required = false)Integer pageNum,@RequestParam(required = false)Integer pageSize) {
        YmShopOrderExample ymShopOrderExample = new YmShopOrderExample();
        YmShopOrderExample.Criteria criteria = ymShopOrderExample.createCriteria();
        if (StringUtils.isNotEmpty(shopOrderStatus)) {
            criteria.andShopOrderStatusEqualTo(shopOrderStatus);
        }
        if (StringUtils.isNotEmpty(shopOrderFlowno)) {
            criteria.andShopOrderFlownoEqualTo(shopOrderFlowno);
        }
        int size = orderService.countByExample(ymShopOrderExample);
        int totalPage = 1;
        if (size % pageSize == 0) {
            totalPage = size / pageSize;
        } else {
            totalPage = size / pageSize + 1;
        }
        if (pageNum != null) {
            if (size > pageSize) {
                ymShopOrderExample.setLimit((pageNum - 1) * pageSize);
            } else {
                ymShopOrderExample.setLimit(0);
            }
            ymShopOrderExample.setOffset(pageSize);
        }
        ymShopOrderExample.setOrderByClause("shop_order_time desc");
        List<YmShopOrder> orders = orderService.selectByExample(ymShopOrderExample);
        for (YmShopOrder order : orders) {
            if (order.getShopOrderTime() != null) {
                order.setShowOrderTime(DateUtils.formatDate(order.getShopOrderTime(),"yyyy-MM-dd HH:mm:ss"));
            }
            if (order.getShopOrderPayTime() != null) {
                order.setShowPayTime(DateUtils.formatDate(order.getShopOrderPayTime(),"yyyy-MM-dd HH:mm:ss"));
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("totalPage", totalPage);
        map.put("totalRecord", size);
        if (orders != null && orders.size() > 0) {
            map.put("list", orders);
            ajaxRes.setSucceed(map, Const.DATA_SUCCEED);
        } else {
            map.put("list", null);
            ajaxRes.setSucceed(map,Const.DATA_SUCCEED);
        }
        return ajaxRes;
    }

    /**
    *
    * 根据订单类型导出订单信息到Excel
    * @author wuyanzu
    * @date 2018/8/6 14:41
    * @param [httpServletResponse, httpServletRequest, orderStatus, ajaxRes]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("outExcel")
    public AjaxRes downExcel(HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest,
                          String orderStatus,AjaxRes ajaxRes){
        if ("".equals(orderStatus) || orderStatus == null) {
            ajaxRes.setFailMsg("参数不能为空");
            return ajaxRes;
        }
        String fileName = getFileName(orderStatus);
        YmShopOrderExample ymShopOrderExample = new YmShopOrderExample();
        List<YmShopOrder> list = null;
        if (!"all".equals(orderStatus)) {
            ymShopOrderExample.createCriteria().andShopOrderStatusEqualTo(orderStatus);
        }
        list = orderService.selectByExample(ymShopOrderExample);
        if (list == null || list.size() == 0) {
            ajaxRes.setFailMsg("暂无"+fileName);
            return ajaxRes;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        fileName = fileName +"_"+ sdf.format(new Date());
        ExcelUtil.exportDataToExcel(list, getHeaders(),"订单信息",httpServletResponse,httpServletRequest,fileName);
        return null;
    }

    /**
    *
    * 根据订单类型判断是否存在
    * @author wuyanzu
    * @date 2018/8/9 15:14
    * @param [ajaxRes, orderStatus]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("countOrder")
    public AjaxRes countOrderByStatus(AjaxRes ajaxRes, String orderStatus) {
        if (StringUtils.isNotEmpty(orderStatus)) {
            YmShopOrderExample orderExample = new YmShopOrderExample();
            if (!"all".equals(orderStatus)){
                orderExample.createCriteria().andShopOrderStatusEqualTo(orderStatus);
            }
            int size = orderService.countByExample(orderExample);
            if (size > 0) {
                ajaxRes.setSucceed(1);
            } else {
                ajaxRes.setRes(0);
            }
        } else {
            ajaxRes.setFailMsg(Const.PARAMETER_NULL);
        }
        return ajaxRes;
    }

    /**
    *
    * 文件上传
    * @author wuyanzu
    * @date 2018/8/3 15:03
    * @param [file, request, ajaxRes]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("uploadExcel")
    public AjaxRes uploadExcel(@RequestParam(name = "file") MultipartFile file, HttpServletRequest request,AjaxRes ajaxRes) throws IOException {
        File tempFile = null;
        if(!file.isEmpty()) {
            String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
            File dir = new File(filePath);
            if(! dir.exists()) {
                dir.mkdir();
            }

            String path = filePath + file.getOriginalFilename();
            //save to the /upload path
            try {
                tempFile = new File(path);
                FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
            } catch (Exception e) {

            }
        }
        if (tempFile != null) {
            List<Object> list = ExcelUtil.importDataFromExcel(new ExcelOrder(), tempFile);
            List<YmShopOrder> orders = new ArrayList<>();
            for (Object o : list) {
                ExcelOrder excelOrder = (ExcelOrder) o;
                try {
                    YmShopOrder order = excelOrderToYmShopOrder(excelOrder);
                    if (StringUtils.isNotEmpty(order.getShopOrderWaybillNumber()) && StringUtils.isNotEmpty(order.getShopOrderCompany())){
                        order.setShopOrderStatus("pendingGoods");
                    }
                    orders.add(order);
                } catch (Exception e) {
                    ajaxRes.setFailMsg("导入Excel失败,日期转换错误");
                    return ajaxRes;
                }
            }
            ajaxRes.setSucceed(orderService.updateBatchByPK(orders));
        }
        return ajaxRes;
    }

    /**
    *
    * 创建购物车订单
    * @author wuyanzu
    * @date 2018/8/24 10:24
    * @param [ajaxRes, totalFee, receivingId]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("shopCarOrder")
    public AjaxRes creatShopCarOrder(AjaxRes ajaxRes,String ymUser,Long totalFee,Long receivingId,Long point) {
        YmUser user = ShopCarController.getYmUser(ymUser);
        System.err.println(user.getUserId()+"==============");
        if (user == null) {
            ajaxRes.setFailMsg("用户信息有误");
            return ajaxRes;
        }
        YmShopReceivingAddress address = getYmShopReceivingAddress(receivingId);
        if (address == null) {
            ajaxRes.setFailMsg("地址不存在");
            return ajaxRes;
        }
        if (weChatFeignClient.getPoint(user.getUserId()) < point) {
            ajaxRes.setFailMsg("积分不足无法购买");
            return ajaxRes;
        }
        YmShopCarExample ymShopCarExample = new YmShopCarExample();
        ymShopCarExample.setDistinct(false);
        ymShopCarExample.createCriteria().andShopCarOpenidEqualTo(user.getRegisterChannelId());
        List<YmShopCar> list = shopCarService.selectByExample(ymShopCarExample);
        if (list != null && list.size() > 0) {
            Long totalPrice = 0L;
            List<ShopCarVo> shopCarVos = new ArrayList<>();
            ShopCarVo shopCarVo = null;
            for (YmShopCar ymShopCar : list) {
                shopCarVo = new ShopCarVo();
                shopCarVo.setShopCarId(ymShopCar.getShopCarId());
                shopCarVo.setShopCarProductNumber(ymShopCar.getShopCarProductNumber());
                YmShopProduct product = productService.selectByPrimaryKey(ymShopCar.getShopCarProductId());
                shopCarVo.setProduct(product);
                shopCarVo.setProductPrice(product.getProductPrice());
                shopCarVo.setProductPoint(product.getProductPoint());
                shopCarVos.add(shopCarVo);
                totalPrice += product.getProductPrice() * ymShopCar.getShopCarProductNumber();
            }
            if (totalFee != totalFee) {
                ajaxRes.setFailMsg("商品价格与实际价格不符");
                return ajaxRes;
            }
            YmShopOrder order = getYmShopOrder(user,totalPrice, address,point);
            if (orderService.insert(order) == 1) {
                int count = 0;
                List<Long> shopCar = new ArrayList<>();
                for (ShopCarVo carVo : shopCarVos) {
                        count += orderProductService.insert(carVo.getShopCarProductNumber(), order.getShopOrderId(), carVo.getProduct(), 1L);
                    shopCar.add(carVo.getShopCarId());
                }
                if (count == shopCarVos.size()) {
                    if (shopCarService.deleteBatchByPK(shopCar) == shopCar.size()) {
                       /* List<YmShopProduct> products = new ArrayList<>();
                        for (ShopCarVo carVo : shopCarVos) {
                            carVo.getProduct().setSalesVolume(carVo.getShopCarProductNumber()+carVo.getProduct().getSalesVolume());
                            carVo.getProduct().setProductNumber(carVo.getProduct().getProductNumber() - carVo.getShopCarProductNumber());
                            products.add(carVo.getProduct());
                        }
                        productService.updateBatchByPK(products);*/
                        ajaxRes.setSucceed(order.getShopOrderId(),"提交订单成功");
                    }
                } else {
                    order.setShopOrderStatus("fail");
                    order.setShopOrderState("N");
                    order.setShopOrderRemarks("生成关联订单失败");
                    orderService.updateByPrimaryKey(order);
                    YmShopOrderProductExample ymShopOrderProductExample = null;
                    for (ShopCarVo carVo : shopCarVos) {
                        ymShopOrderProductExample = new YmShopOrderProductExample();
                        ymShopCarExample.createCriteria().andShopCarProductIdEqualTo(carVo.getShopCarProductId());
                        orderProductService.deleteByPrimaryKey(ymShopOrderProductExample);
                    }
                    ajaxRes.setFailMsg("提交订单失败");
                }
            } else {
                ajaxRes.setFailMsg("提交订单失败");
            }
        } else {
            ajaxRes.setFailMsg("购物车暂无商品");
        }
        return ajaxRes;
    }

    /**
    *
    * 创建代付款订单
    * @author wuyanzu
    * @date 2018/8/2 10:47
    * @param [userId, openid, totalFee, productId, productNum, price]
    * @return java.lang.String
    */
    @RequestMapping("add")
    public AjaxRes crateOrder(AjaxRes ajaxRes,String ymUser,Long totalFee, Long productId,@RequestParam(required = false) Long point,
                              Long productNum, Long price,Long receivingId,Long shopOrderPayMethod) {
        YmUser user = ShopCarController.getYmUser(ymUser);
        System.err.println(user.getUserId()+"==============");
        if (user == null) {
            ajaxRes.setFailMsg("用户信息有误");
            return ajaxRes;
        }
        YmShopProduct product = productService.selectByPrimaryKey(productId);
        YmShopReceivingAddress address = getYmShopReceivingAddress(receivingId);
        if (product == null || address == null) {
            ajaxRes.setFailMsg("商品或者地址不存在");
            return ajaxRes;
        } else {
            String res = verification(totalFee, product, productNum, price,receivingId,shopOrderPayMethod);
            if (res != null && !"".equals(res)) {
                ajaxRes.setFailMsg(res);
                return ajaxRes;
            }
        }
        List<YmShopOrderProduct> ymShopOrderProducts = new ArrayList<>();
        YmShopOrderProduct ymShopOrderProduct = new YmShopOrderProduct();
        ymShopOrderProduct.setShopProductId(productId);
        ymShopOrderProduct.setShopProductNumber(productNum);
        ymShopOrderProducts.add(ymShopOrderProduct);
        YmShopOrder order = getYmShopOrder(user,totalFee,address,point);
        if (shopOrderPayMethod == 0) {
            if (weChatFeignClient.getPoint(user.getUserId()) < product.getProductPoint()) {
                ajaxRes.setFailMsg("积分不足无法购买");
                return ajaxRes;
            }
            order.setShopOrderPoint(totalFee);
            order.setShopOrderTotalcost(0L);
            order.setShopOrderProductcost(0L);
            order.setShopOrderPayMethod("point");
        }
        if (orderService.insert(order) == 1) {
            if (shopOrderPayMethod == 0) {
                 if (creatPointOrder(user.getUserId(),order, ymShopOrderProducts)) {
                    product.setSalesVolume(product.getSalesVolume() + productNum);
                    product.setProductNumber(product.getProductNumber() - productNum);
                    productService.updateByPrimaryKey(product);
                    ajaxRes.setSucceed(order.getShopOrderId(),"生成订单成功");
                } else {
                    order.setShopOrderRemarks("积分购买失败订单");
                    order.setShopOrderState("N");
                    order.setShopOrderStatus("fail");
                    orderService.updateByPrimaryKey(order);
                    ajaxRes.setFailMsg("生成订单失败");
                }
            } else if(shopOrderPayMethod == 1){
                if (weChatFeignClient.getPoint(user.getUserId()) < point) {
                    ajaxRes.setFailMsg("积分不足无法购买");
                    return ajaxRes;
                }
                if (orderProductService.insert(productNum, order.getShopOrderId(), product, 1L) == 1) {
                    /*product.setSalesVolume(product.getSalesVolume() + productNum);
                    product.setProductNumber(product.getProductNumber() - productNum);
                    productService.updateByPrimaryKey(product);*/
                    ajaxRes.setSucceed(order.getShopOrderId(),"生成订单成功");
                } else {
                    order.setShopOrderRemarks("创建订单商品关联信息失败");
                    order.setShopOrderState("N");
                    order.setShopOrderStatus("fail");
                    orderService.updateByPrimaryKey(order);
                    ajaxRes.setFailMsg("生成订单失败");
                }
            }
        } else {
            ajaxRes.setFailMsg("生成订单失败");
        }
        return ajaxRes;
    }

    public YmShopOrder getYmShopOrder(YmUser ymUser,Long shopOrderProductcost, YmShopReceivingAddress address,Long point) {
        YmShopOrder order = new YmShopOrder();
        Date date = new Date();
        //创建订单时间
        order.setShopOrderTime(date);
        //交易流水号
        order.setShopOrderFlowno(getUUID(date));
        //是否是展示
        order.setShopOrderState("Y");
        //订单状态
        order.setShopOrderStatus("pendingPayment");
        //订单总金额
        order.setShopOrderTotalcost(shopOrderProductcost);
        //商品总金额
        order.setShopOrderProductcost(shopOrderProductcost);
        //订单积分
        order.setShopOrderPoint(point);
        //用户ID
        order.setUserId(ymUser.getUserId());
        //微信用户openID
        order.setWxuserId(ymUser.getRegisterChannelId());
        //运费
        order.setShopOrderTansportationcost(0L);
        //详细地址
        order.setUserReceivingAddress(address.getDetailedAddress().replace(",", " ")+ " "+address.getReceiverAddress());
        //收货人姓名
        order.setShopOrderUserName(address.getReceiverName());
        //收货人电话
        order.setShopOrderUserMobile(address.getReceiverPhone());
        //商品重量
        order.setShopOrderTotalweight(0L);
        return order;
    }

    public YmShopReceivingAddress getYmShopReceivingAddress(Long receivingId) {
        return receivingAddressService.selectByPrimaryKey(receivingId);
    }


    private boolean creatPointOrder(Long userId,YmShopOrder order,List<YmShopOrderProduct> ymShopOrderProducts) {
        if (weChatFeignClient.insertUserPoint(userId, "积分兑换商品", null, "-" + order.getShopOrderPoint()) == 1) {
            order.setShopOrderPayTime(new Date());
            order.setShopOrderStatus("pendingDelivery");
            if (orderService.updateByPrimaryKey(order) == 1) {
                int count = 0;
                for (YmShopOrderProduct orderProduct : ymShopOrderProducts) {
                    YmShopProduct product = productService.selectByPrimaryKey(orderProduct.getShopProductId());
                    count += orderProductService.insert(orderProduct.getShopProductNumber(), order.getShopOrderId(), product,0L);
                }
                if (count == ymShopOrderProducts.size()) {
                    return true;
                } else {
                    weChatFeignClient.insertUserPoint(userId, "积分兑换商品失败", null, "+" + order.getShopOrderPoint());
                    return false;
                }
            } else {
                weChatFeignClient.insertUserPoint(userId, "积分兑换商品失败", null, "+" + order.getShopOrderPoint());
                return false;
            }
        } else {
            return false;
        }
    }

    /**
    *
    * 根据订单类型返回Excel文件名
    * @author wuyanzu
    * @date 2018/8/6 18:08
    * @param [orderStatus]
    * @return java.lang.String
    */
    public String getFileName(String orderStatus) {
        String fileName;
        switch (orderStatus) {
            case "pendingPayment":
                fileName = "待付款订单信息";
                break;
            case "pendingDelivery":
                fileName = "待发货订单信息";
                break;
            case "pendingGoods":
                fileName = "待收货订单信息";
                break;
            case "pendingEvaluated":
                fileName = "待评价订单信息";
                break;
            case "theEnd":
                fileName = "已完成订单信息";
                break;
            case "fail":
                fileName = "失败订单信息";
                break;
            default:
                fileName = "订单信息";
        }
        return fileName;
    }

    /**
    *
    * 生成订单ExcelHeaders
    * @author wuyanzu
    * @date 2018/8/6 18:04
    * @param []
    * @return java.lang.String[]
    */
    public String[] getHeaders(){
        String[] headers = new String[22];
        headers[0] = "订单编号";
        headers[1] = "订单流水号";
        headers[2] = "下单时间";
        headers[3] = "快递单号";
        headers[4] = "快递公司名称";
        headers[5] = "订单总金额";
        headers[6] = "商品总金额";
        headers[7] = "订单总积分";
        headers[8] = "运费";
        headers[9] = "支付方式";
        headers[10] = "支付时间";
        headers[11] = "订单状态";
        headers[12] = "用户ID";
        headers[13] = "微信用户openID";
        headers[14] = "收货地址";
        headers[15] = "订单重量";
        headers[16] = "预支付ID";
        headers[17] = "微信交易流水号";
        headers[18] = "备注";
        headers[19] = "收货人姓名";
        headers[20] = "收货人电话";
        headers[21] = "订单是否有效";
        return headers;
    }

    /**
    *
    * 将Excel读取的内容放到订单对象
    * @author wuyanzu
    * @date 2018/8/6 16:13
    * @param [order]
    * @return com.cn.springcloudshop.model.YmShopOrder
    */
    public YmShopOrder excelOrderToYmShopOrder(ExcelOrder order) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        YmShopOrder ymShopOrder = new YmShopOrder();
        ymShopOrder.setShopOrderId(Long.valueOf(order.getShopOrderId()));
        ymShopOrder.setShopOrderFlowno(order.getShopOrderFlowno());
        ymShopOrder.setShopOrderTime(sdf.parse(order.getShopOrderTime()));
        ymShopOrder.setShopOrderWaybillNumber(order.getShopOrderWaybillNumber());
        ymShopOrder.setShopOrderCompany(order.getShopOrderCompany());
        ymShopOrder.setShopOrderTotalcost(Long.valueOf(order.getShopOrderTotalcost()));
        ymShopOrder.setShopOrderProductcost(Long.valueOf(order.getShopOrderProductcost()));
        ymShopOrder.setShopOrderPoint(Long.valueOf(order.getShopOrderPoint()));
        ymShopOrder.setShopOrderTansportationcost(0L);
        ymShopOrder.setShopOrderPayMethod(order.getShopOrderPayMethod());
        ymShopOrder.setShopOrderPayTime(sdf.parse(order.getShopOrderPayTime()));
        ymShopOrder.setShopOrderStatus(order.getShopOrderStatus());
        ymShopOrder.setUserId(Long.valueOf(order.getUserId()));
        ymShopOrder.setWxuserId(order.getWxuserId());
        ymShopOrder.setUserReceivingAddress(order.getUserReceivingAddress());
        ymShopOrder.setShopOrderTotalweight(0L);
        ymShopOrder.setShopOrderPrepayid(order.getShopOrderPrepayid());
        ymShopOrder.setShopOrderWaterid(order.getShopOrderWaterid());
        ymShopOrder.setShopOrderRemarks(order.getShopOrderRemarks());
        ymShopOrder.setShopOrderUserName(order.getShopOrderUserName());
        ymShopOrder.setShopOrderUserMobile(order.getShopOrderUserMobile());
        ymShopOrder.setShopOrderState(order.getShopOrderState());
        return ymShopOrder;
    }

    /**
    *
    * 生成订单流水号
    * @author wuyanzu
    * @date 2018/8/2 10:47
    * @param [date]
    * @return java.lang.String
    */
    public String getUUID(Date date) {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        return (String.valueOf(date.getTime()) + uuid.substring(0, 6));
    }

    /**
    *
    * 创建订单参数校验
    * @author wuyanzu
    * @date 2018/8/2 10:47
    * @param [userId, openid, totalFee, productId, productNum, price]
    * @return java.lang.String
    */
    public String verification(Long totalFee, YmShopProduct product, Long productNum, Long price,Long receivingId,Long shopOrderPayMethod){
        String res = null;
        if (totalFee == null || product == null || productNum
                == null || price == null || receivingId == null || shopOrderPayMethod == null) {
            res = "购买失败";
            return res;
        }
        //直接购买
        if (shopOrderPayMethod == 1) {
            if (!price.equals(product.getProductPrice())) {
                res = "商品价格与实际价格不符";
                return res;
            }
            if (totalFee != price * productNum) {
                res = "商品价格与实际金额不符";
                return res;
            }//积分兑换
        } else if (shopOrderPayMethod == 0) {
            if (!price.equals(product.getProductPoint())) {
                res = "商品价格与实际价格不符";
                return res;
            }
            if (totalFee != price * productNum) {
                res = "商品价格与实际金额不符";
                return res;
            }
        }
        if (product.getOffdate() != null && product.getOffdate().getTime() <= new Date().getTime()) {
            res = "商品已下架";
            return res;
        }
        if (product.getSalesVolume() == null) {
            product.setSalesVolume(0L);
        }
        if (product.getProductNumber() != null && product.getProductNumber() - productNum < 0) {
            res = "商品已售空";
            return res;
        }
        if (product.getProductNumber() != null && product.getProductNumber() < productNum) {
            res = "商品数量不足,仅剩" + product.getProductNumber() + "件";
            return res;
        }
        return res;
    }
}
